import hashlib
import random

from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password, check_password
from . import models


# Create your views here.


def index(request):
    return render(request, 'index.html')


def login(request):
    if request.method == 'GET':
        pass
        return render(request, 'login.html')
    elif request.method == 'POST':
        context = {
            'message': ''
        }
        username = request.POST.get('username')
        password = request.POST.get('password')

        # 验证用户名和密码
        user = models.User.objects.filter(name=username).first()
        if user:
            # hash加密判断
            if _hash_password(password) == user.hash_password:
            # 明文密码判断
            # if user.password == password:
                context['message'] = '登录成功'
                # 服务器设置session和其他用户信息
                request.session['is_login'] = True
                request.session['username'] = user.name
                request.session['userid'] = user.id
                return redirect('/index/')  # 返回的响应中包含set-cookie(session='dfbnmCD')，浏览器接收到响应后会把sessionid存到cookie中
            else:
                context['message'] = '密码错误'
                return render(request, 'login.html', context=context)
        else:
            context['message'] = '您还未注册'
        return render(request, 'login.html', context=context)


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    elif request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        email = request.POST.get('email')
        # 表单验证 后端
        # if not (username.strip() and password.strip() and email.strip()):
        #     print('某个字段为空')
        #     return render('/register', context={'message': '某个字段为空'})
        # if len(username) > 20 or len(password) > 20 or len(email):
        #     print('用户名或密码或邮箱长度不能超过20')
        # 写数据库 后端
        user = models.User.objects.filter(email=email).first()
        if user:
            '用户已注册'
            return render(request, 'register.html', context={'message': '用户已注册'})

        # 加密密码
        hash_password = _hash_password(password)
        #
        try:
            user = models.User(name=username, password=password, hash_password=hash_password, email=email)
            user.save()
            print('保存成功')
            return render(request, 'login.html', context={'message': '注册成功，请继续登录'})
        except Exception as e:
            print('数据库保存失败', e)
            return redirect('/register/')


def logout(request):
    """退出登录"""
    if not request.session.get('is_login', None):
        return redirect('/index/')

    # 清除session 退出登录
    request.session.flush()   # 清除用户sessionid对应的所有sessiondata
    # del request.session['userid']  # 删除某个session键值
    return redirect('/index/')


def _hash_password(password):
    md5 = hashlib.sha256()
    salt = chr(random.randint(65, 122))
    md5.update((salt+password).encode('utf-8'))
    return md5.hexdigest()


# 查询数据库，比较数据
#         res = models.User.objects.filter(name=username, password=password).first()

